package com.hu.juc.day01.T1;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

class Ticket {
    private Integer ticket = 0;

    private Lock lock = new ReentrantLock();
    private Condition condition = lock.newCondition();

    public void dec() {
        lock.lock();
        try {
            while (ticket == 0) {
                //this.wait();
                condition.await();
            }
            //2.干活
            ticket--;
            System.out.println(Thread.currentThread().getName() + "\t" + ticket);
            //3.通知
            //this.notifyAll();
            condition.signalAll();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void inc() {
        lock.lock();
        try {
            while (ticket != 0) {
                //this.wait();
                condition.await();
            }
            //2.干活
            ticket++;
            System.out.println(Thread.currentThread().getName() + "\t" + ticket);
            //3.通知
            //this.notifyAll();
            condition.signalAll();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
    /*public synchronized void dec() throws InterruptedException {
        //1.判断
        while (ticket == 0) {
            this.wait();
        }
        //2.干活
        ticket--;
        System.out.println(Thread.currentThread().getName() + "\t" + ticket);
        //3.通知
        this.notifyAll();
    }

    public synchronized void inc() throws InterruptedException {
        //1.判断
        while (ticket != 0) {
            this.wait();
        }
        //2.干活
        ticket++;
        System.out.println(Thread.currentThread().getName() + "\t" + ticket);
        //3.通知
        this.notifyAll();
    }*/
}